package cn.myfirefly.core.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.myfirefly.core.Const;
import cn.myfirefly.utils.VerifyCodeUtils;

public class VerifyCodeServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = -3141732200203305693L;

	private static final String PARAM_HEIGHT = "height"; 
	private static final String PARAM_WIDTH = "width";
	private static final String PARAM_TEXT_LENGTH="text_length";
	protected int _width = 200; //宽度 默认为200
	protected int _height = 50; //高度 默认为50
	protected int _text_length = 4; // 验证码长度
	
	public void init() throws ServletException {
    	if (getInitParameter(PARAM_HEIGHT) != null) {
    		_height = Integer.valueOf(getInitParameter(PARAM_HEIGHT));
    	}
    	
    	if (getInitParameter(PARAM_WIDTH) != null) {
    		_width = Integer.valueOf(getInitParameter(PARAM_WIDTH));
    	}
    	if (getInitParameter(PARAM_TEXT_LENGTH) != null) {
    		_text_length = Integer.valueOf(getInitParameter(PARAM_TEXT_LENGTH));
    	}
	}
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
	          throws ServletException, IOException {
		String code = VerifyCodeUtils.generateVerifyCode(_text_length);
		req.getSession().setAttribute(Const.VERIFY_CODE_NAME, code);
		VerifyCodeUtils.outputImage(_width, _height, resp.getOutputStream(), code);
	}
}
